import 'dart:io';
import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/api/feed_back_api.dart';
import 'package:mi_mang_flutter/api/upload_api.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:image_picker/image_picker.dart';

class FeedbackPage extends StatefulWidget {
  @override
  _FeedbackPageState createState() => _FeedbackPageState();
}

class _FeedbackPageState extends State<FeedbackPage>
    with SingleTickerProviderStateMixin {
  final ImagePicker _picker = ImagePicker();

  /// 选择的图片列表
  List<File> _imageList = [];

  List<int?> _screenshotIdsList = [];

  final FocusNode complaintsFocus = FocusNode();
  TextEditingController _txtController = TextEditingController();

  TextEditingController _emailController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(i18n(context).feedback),
        centerTitle: true,
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            child: _buildBody(),
          ),
          _buildSubmitBtn(),
        ],
      ),
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.all(Dimens.gapDp15),
        child: Column(
          children: <Widget>[
            _buildTextField(),
            Gaps.vGap15,
            _buildPhoneNum(),
          ],
        ),
      ),
    );
  }

  /// 反馈内容布局
  Widget _buildTextField() {
    return Material(
      borderRadius: BorderRadius.circular(Dimens.gapDp5),
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(Dimens.gapDp5),
            child: TextField(
              maxLines: 12,
              maxLength: 500,
              controller: _txtController,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.all(Dimens.gapDp10),
                hintText: '你的建议将帮助米茫不迷茫',
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
              ),
            ),
          ),
          _buildListPic(),
        ],
      ),
    );
  }

  /// 图片列表布局
  Widget _buildListPic() {
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      padding: const EdgeInsets.fromLTRB(8.0, 10.0, 8.0, 15.0),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
      ),
      // 小于4个元素的时候显示“+”占位图
      itemCount:
          _imageList.length < 4 ? _imageList.length + 1 : _imageList.length,
      itemBuilder: (_, index) {
        if (_imageList.length < 4 && _imageList.length == index) {
          return _placeholderImage();
        } else {
          return _imageItem(_imageList[index], index);
        }
      },
    );
  }

  /// 每个图片项
  Widget _imageItem(File file, int index) {
    return Container(
      padding: EdgeInsets.all(5.0),
      child: Stack(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
            child: Image.file(
              file,
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            top: 5.0,
            right: 5.0,
            child: InkWell(
              child:
                  Icon(Icons.highlight_off, size: 24, color: Colors.grey[200]),
              onTap: () {
                setState(() {
                  _imageList.removeAt(index);
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 选择图片的“+”占位图
  Widget _placeholderImage() {
    return GestureDetector(
      child: Padding(
        padding: EdgeInsets.all(5.0),
        child: loadImage("setting/selectpic"),
      ),
      onTap: _selectPic,
    );
  }

  /// 邮箱布局
  Widget _buildPhoneNum() {
    return Material(
      borderRadius: BorderRadius.circular(Dimens.gapDp5),
      child: Container(
        height: 50.0,
        child: TextField(
          controller: _emailController,
          textInputAction: TextInputAction.done,
          decoration: InputDecoration(
            contentPadding: EdgeInsets.all(10.0),
            hintText: "邮箱或者QQ号码 (选填)",
            counterText: "",
            border: InputBorder.none,
            focusedBorder: InputBorder.none,
            enabledBorder: InputBorder.none,
          ),
        ),
      ),
    );
  }

  /// 提交按钮布局
  Widget _buildSubmitBtn() {
    return Padding(
      padding: EdgeInsets.all(Dimens.gapDp15),
      child: ElevatedButton.icon(
        icon: Icon(Icons.done),
        label: Text(i18n(context).submit),
        onPressed: _submitAction,
      ),
    );
  }

  /// 选择图片
  void _selectPic() {
    FocusManager.instance.primaryFocus?.unfocus();
    _picker
        .pickImage(
      source: ImageSource.gallery,
      maxWidth: 1000.0,
      maxHeight: 1000.0,
      imageQuality: 50,
    )
        .then((pickedFile) {
      if (pickedFile != null) {
        var file = File(pickedFile.path);
        setState(() {
          _imageList.add(file);
        });
        upload(file, storeType: 1).then((val) {
          _screenshotIdsList.add(val.data!.id);
        });
      } else {
        Toast.showInfo("未选中图片资源");
      }
    });
  }

  /// 提交按钮事件
  void _submitAction() async {
    FocusManager.instance.primaryFocus?.unfocus();
    // 判断投诉内容是否为空，必填项
    if (_txtController.text.length < 10) {
      Toast.showWarn("请填写不小于10字的投诉内容");
      return;
    }
    // 判断是否长传了图片(这里是统一文件上传的实现,避免上传不必要的图片)
    // if (_imageList.length > 0) {
    //   batchUpload(_imageList).then((val) {
    //     print(val.data);
    //   });
    // }
    _saveFeedBack(screenshotIds: _screenshotIdsList);
  }

  void _saveFeedBack({List<int?>? screenshotIds}) {
    String contact = _emailController.text;
    FeedBackApi.save(_txtController.text, contact, screenshotIds ?? [])
        .then((val) {
      Toast.showInfo("感谢您珍贵的反馈意见");
      Navigator.maybePop(context);
    });
  }
}
